package com.ruoyi.web.controller.dll;

import cn.dev33.satoken.annotation.SaIgnore;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import cn.hutool.log.StaticLog;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.system.domain.bank.BankCreditCard;
import com.ruoyi.system.domain.bank.FtTransactionCode;
import com.ruoyi.system.domain.bank.SyUserLog;
import com.ruoyi.system.domain.bank.SysBank;
import com.ruoyi.system.service.ISysDeptService;
import com.ruoyi.web.controller.mqtt.DefaultFuture;
import com.ruoyi.web.controller.mqtt.MqttSender;
import com.ruoyi.web.controller.mqtt.Request;
import com.ruoyi.web.controller.mqtt.Response;
import lombok.RequiredArgsConstructor;
import org.apache.commons.compress.utils.Lists;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.UnsupportedEncodingException;
import java.sql.*;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

/**
 * 个人信息 业务处理
 *
 * @author Lion Li
 */
@Validated
@RequiredArgsConstructor
@RestController
@SaIgnore
@RequestMapping("/api/dll")
public class DllController extends BaseController {
    private final ISysDeptService deptService;
    private final MqttSender mqttSender;

    @GetMapping(value = "/pay")
    public R<String> pay(String input, String type, String param, String no, SyUserLog syUserLog) {


//        String input = "0012345678234567890000000000000120141212123412341234123456000                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  ";
        Response r= syncSent(input, no);
        byte[] tmpstr = Convert.toPrimitiveByteArray(r.getData());
        int iret = Integer.parseInt(r.getMsg());
        if (iret != 0) {
            return R.fail("函数调用失败");
        }
        try {
            int[] lens = {2, 4, 20, 6, 12, 40, 15, 8, 6, 4, 6, 12, 6, 4, 3, 12, 2, 200, 50, 50, 50, 1, 1, 50, 200, 8,
                20};

            List<String> list = Lists.newArrayList();

            int num = 0;
            for (int i = 0; i < 27; i++) {
                byte[] destArrays = new byte[lens[i]]; // 动态创建数组
                System.arraycopy(tmpstr, num, destArrays, 0, lens[i]); // 拷贝
                num += lens[i];

                //结果自己去做处理或者插入数据库
                String strtemp = new String(destArrays, "GBK");
                list.add(strtemp);
            }
            String join = String.join(",", list);
            StaticLog.info("dll返回结果:{}", join);
            String[] data = join.split(",");
            if (data[0].equals("00")) {
                if (type.equals("21")) {
                    //预授权数据库操作
                    SysBank sysBank = new SysBank();
                    BankCreditCard bankCreditCard = new BankCreditCard();

                    String[] paramList = param.split(",");
                    String reservationCode = paramList[0];   //预定号
                    System.out.println(reservationCode + "这是预定号");
                    String syOperator = paramList[1];        //操作员
                    String approveAmount = paramList[2];  //授权金额
                    String voucherNo =data[3];
                    //获取ddl返回结果里面的参数
                    //银行卡 授权金额 授权码 付款方式


                    String creditCardNo = data[2];


                    String approveCode = data[12];
                    String banTrxCode = data[11];

                    //[11]
                    bankCreditCard.setCode(banTrxCode);
                    bankCreditCard.setFolioID(reservationCode);
                    bankCreditCard.setPosAmount(approveAmount);
                    bankCreditCard.setOperator("Admin");
                    bankCreditCard.setPosType("GBD");
                    bankCreditCard.setCreditCardNO(creditCardNo);
                    deptService.insertBankCard(bankCreditCard);

                    sysBank.setReservationCode(reservationCode);
                    sysBank.setInsertUser("Admin");
                    sysBank.setPaymentType("GBD");
                    sysBank.setCreditCardNo(creditCardNo);
                    sysBank.setApproveCode(approveCode);
                    sysBank.setApproveAmount(approveAmount);
                    sysBank.setBankTrxCode(banTrxCode);
                    //insert into rvCreditCard (ReservationCode,PaymentType,CreditCardNo,ApproveAmount,ApproveCode,InsertUser,InsertTime)
                    //       select @ReservationCode,@PaymentType,@CreditCardNo,@ApproveAmount,@ApproveCode,@InsertUser,@InsertTime,
                    deptService.insertBank(sysBank);

                }
                if (type.equals("23")) {
                    Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
                    String url = "jdbc:sqlserver://172.31.0.17:1433;DatabaseName=Training;trustServerCertificate=true;";
                    Connection conn = DriverManager.getConnection(url, "sa", "SUNSHINE@123,.HNA");

                    String[] paramList = param.split(",");
                    String reservationCode = paramList[0];   //预定号
                    System.out.println(reservationCode + "这是预定号");
                    String syOperator = paramList[1];        //操作员
                    String Amount = paramList[2];  //金额
                    String creditCardNo = data[2];
                    String voucherNo =data[3];
                    String dan=data[11]; //单据号
                    String banTrxCode = paramList[3];
                    String pay = paramList[4];



                    PreparedStatement ps = conn.prepareStatement("{call dbo.ftPayment(?,?,?,?,?,?,?,?,?,?,?)}");
                    ps.setString(1, pay);
                    ps.setString(2, Amount);
                    ps.setString(3, "0|0|0");
                    ps.setString(4, dan);
                    ps.setString(5, null);
                    ps.setString(6, null);
                    ps.setString(7, "*");
                    ps.setString(8, "*");
                    ps.setInt(9, 1);
                    ps.setInt(10, Integer.parseInt(reservationCode));
                    ps.setString(11, "Admin");
                     ps.execute();



                    PreparedStatement pstow = conn.prepareStatement("{call dbo.FTPaymentUpdate(?,?,?,?,?,?)}");
                    pstow.setString(1, pay);
                    pstow.setString(2, Amount);
                    pstow.setString(3, creditCardNo);
                    pstow.setString(4, reservationCode);
                    pstow.setString(5, "Admin");
                    pstow.setString(6, banTrxCode);
                     pstow.execute();


                    deptService.updateBankCard(voucherNo,banTrxCode);
                    int i = deptService.InsertSyUserLog(syUserLog);
                    System.out.println("新增"+i);
                    ps.close();
                    pstow.close();
                }
                if (type.equals("25")) {
                    String[] paramList = param.split(",");
                    String bankTrxCode = paramList[2];
                    deptService.deleteBank(bankTrxCode);
                    deptService.deleteBankCard(bankTrxCode);

                }
                if (type.equals("26")) {
                    Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
                    String url = "jdbc:sqlserver://172.31.0.17:1433;DatabaseName=Training;trustServerCertificate=true;";
                    Connection conn = DriverManager.getConnection(url, "sa", "SUNSHINE@123,.HNA");
                    String[] paramList = param.split(",");
                    String bankTrxCode = paramList[2];
                    String Amount = paramList[2];  //金额
                    String pay = paramList[4];
                    double i = Double.parseDouble(Amount);
                    double negativeNumber = -i;  // 负数
                    String reservationCode = paramList[0];   //预定号


                    BankCreditCard bankCreditCard = deptService.getBankCreditCard(bankTrxCode);

                    PreparedStatement ps = conn.prepareStatement("{call dbo.ftPayment(?,?,?,?,?,?,?,?,?,?,?)}");
                    ps.setString(1, pay);
                    ps.setString(2, String.valueOf(negativeNumber));
                    ps.setString(3, "0|0|0");
                    ps.setString(4, null);
                    ps.setString(5, null);
                    ps.setString(6, null);
                    ps.setString(7, "*");
                    ps.setString(8, "*");
                    ps.setInt(9, 1);
                    ps.setInt(10, Integer.parseInt(reservationCode));
                    ps.setString(11, "Admin");


                    ResultSet rs = ps.executeQuery();
                    rs.close();

                }
                if (type.equals("00")) {
                    Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
                    String url = "jdbc:sqlserver://172.31.0.17:1433;DatabaseName=Training;trustServerCertificate=true;";
                    Connection conn = DriverManager.getConnection(url, "sa", "SUNSHINE@123,.HNA");

                    String[] paramList = param.split(",");
                    String reservationCode = paramList[0];   //预定号
                    System.out.println(reservationCode + "这是预定号");
                    String syOperator = paramList[1];        //操作员
                    String Amount = paramList[2];  //金额
                    String creditCardNo = data[2];
                    String pingzheng = data[3];
                    String banTrxCode = data[11];
                    String voucherNo =data[3];
                    String pay = paramList[4]; //付款代码


                    PreparedStatement ps = conn.prepareStatement("{call dbo.ftPayment(?,?,?,?,?,?,?,?,?,?,?)}");
                    ps.setString(1, "9004");
                    ps.setString(2, Amount);
                    ps.setString(3, "0|0|0");
                    ps.setString(4, pingzheng);
                    ps.setString(5, null);
                    ps.setString(6, null);
                    ps.setString(7, "*");
                    ps.setString(8, "*");
                    ps.setInt(9, 1);
                    ps.setInt(10, Integer.parseInt(reservationCode));
                    ps.setString(11, "Admin");
                    ps.execute();

                    PreparedStatement pstow = conn.prepareStatement("{call dbo.FTPaymentUpdate(?,?,?,?,?,?)}");
                    pstow.setString(1, "9105");
                    pstow.setString(2, Amount);

                    pstow.setString(3, creditCardNo);
                    pstow.setString(4, "5205");
                    pstow.setString(5, "Admin");
                    pstow.setString(6, banTrxCode);
                    pstow.execute();
                    deptService.updateBankCard(voucherNo,pay);


                }
                if (type.equals("01")) {
                    Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
                    String url = "jdbc:sqlserver://172.31.0.17:1433;DatabaseName=Training;trustServerCertificate=true;";
                    Connection conn = DriverManager.getConnection(url, "sa", "SUNSHINE@123,.HNA");
                    String[] paramList = param.split(",");
                    String bankTrxCode = paramList[2];
                    String Amount = paramList[2];  //金额
                    String pay = paramList[4];
                    double i = Double.parseDouble(Amount);
                    double negativeNumber = -i;  // 负数
                    String reservationCode = paramList[0];   //预定号

                    BankCreditCard bankCreditCard = deptService.getBankCreditCard(bankTrxCode);

                    PreparedStatement ps = conn.prepareStatement("{call dbo.ftPayment(?,?,?,?,?,?,?,?,?,?,?)}");
                    ps.setString(1, pay);
                    ps.setString(2, String.valueOf(negativeNumber));
                    ps.setString(3, "0|0|0");
                    ps.setString(4, null);
                    ps.setString(5, null);
                    ps.setString(6, null);
                    ps.setString(7, "*");
                    ps.setString(8, "*");
                    ps.setInt(9, 1);
                    ps.setInt(10, Integer.parseInt(reservationCode));
                    ps.setString(11, "Admin");
                    ps.execute();


                }
                return R.ok(data[5]);
            }
            return R.fail(data[5]);
            //自己插入数据库
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            return R.fail();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        }
    }

    @GetMapping("/select")
    public String select() {
        List<FtTransactionCode> ft = deptService.getFtTransactionCodeAll();
        return JSONUtil.toJsonStr(ft);
    }


    private Response syncSent(String cmd, String no) {
        Request req = new Request(StrUtil.uuid());
        req.setData(cmd);
        String topic = StrUtil.format("topic/request/pos/{}", no);
        StaticLog.info("下发的指令=>{}=>{}", topic, cmd);
        mqttSender.sendWithTopicAndQos(topic, 0, JSONUtil.toJsonStr(req));

        String msgId = String.valueOf(req.getMId());
        CompletableFuture<Response> cf = new DefaultFuture(msgId).thenApply(obj -> (Response) obj);
        try {
            Response msg = cf.get();
            DefaultFuture.cancel(msgId);
            return  msg;
        } catch (InterruptedException | ExecutionException e) {
            DefaultFuture.cancel(msgId);
        }
        throw new ServiceException("设备通讯失败");


    }
}
